#region Using

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

#endregion

namespace SemanticEngine
{
	public class WebHelper
	{

		/// <summary>
		/// Downloads a web page from the Internet and returns the HTML as a string. .
		/// </summary>
		/// <param name="url">The URL to download from.</param>
		/// <returns>The HTML or null if the URL isn't valid.</returns>
		public static string DownloadWebPage(Uri url)
		{
			try
			{
				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
				request.Headers["Accept-Encoding"] = "gzip";
				request.Headers["Accept-Language"] = "en-us";
				request.Credentials = CredentialCache.DefaultNetworkCredentials;
				request.AutomaticDecompression = DecompressionMethods.GZip;

				using (WebResponse response = request.GetResponse())
				{
					using (StreamReader reader = new StreamReader(response.GetResponseStream()))
					{
						return reader.ReadToEnd();
					}
				}
			}
			catch (WebException)
			{
				return null;
			}
		}

		public void DownloadWebPageAsync(Uri url)
		{
			HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
			request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;)";
			request.Timeout = 1500;
			request.BeginGetResponse(EndDownloadWebPageAsync, request);
		}

		private void EndDownloadWebPageAsync(IAsyncResult result)
		{
			HttpWebRequest request = (HttpWebRequest)result.AsyncState;
			using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
			using (StreamReader reader = new StreamReader(response.GetResponseStream()))
			{
				OnDownloadComplete(reader.ReadToEnd(), request.RequestUri);
			}
		}

		public event EventHandler<DownloadEventArgs> DownloadComplete;
		/// <summary>
		/// Occurs when the class is DownloadComplete
		/// </summary>
		protected void OnDownloadComplete(string html, Uri url)
		{
			if (DownloadComplete != null)
			{
				DownloadComplete(html, new DownloadEventArgs(url, html));
			}
		}

		public static Uri MakeAbsolute(Uri url, Uri baseUrl)
		{
			if (!url.IsAbsoluteUri)
			{
				string absoluteUrl = null;
				if (!url.ToString().StartsWith("/", StringComparison.Ordinal))
					absoluteUrl = (baseUrl + url.ToString());
				else
					absoluteUrl = baseUrl.Scheme + "://" + baseUrl.Authority + url;

				return new Uri(absoluteUrl);
			}

			return url;
		}

	}
}
